
import json
import pandas as pd


def data2json(data):
    pairs = data.strip().split("\n")

    # 创建一个空的字典来存储键值对
    json_data = {}

    # 遍历键值对，将其添加到字典中
    for pair in pairs:
        key, value = pair.split(": ", 1)
        json_data[key] = value

    # 将字典转换为JSON格式
    return json_data


def params2json(params):
    # 将数据分割成键值对
    pairs = params.strip().split("&")

    # 创建一个空的字典来存储键值对
    json_data = {}

    # 遍历键值对，将其添加到字典中
    for pair in pairs:
        key, value = pair.split("=", 1)
        json_data[key] = value

    # 将字典转换为JSON格式
    return json_data


def excel2json(file_name, sheet_name='Sheet1'):
    data_arr = []
    data = pd.read_excel(file_name, sheet_name=sheet_name)
    # 打印DataFrame每一行的数据
    for _, row in data.iterrows():
        header = {}
        params = {}
        data = {}
        if not pd.isnull(row['header']):
            header = data2json(row['header'])
        if not pd.isnull(row['params']):
            params = params2json(row['params'])
        if not pd.isnull(row['data']):
            data = json.loads(row['data'])
        data_obj = {
            "header": header,
            "params":  params,
            "data": data,
            'phone': row['phone']
        }
        data_arr.append(data_obj)
        print(data_arr)
    return data_arr


# excel2json('data.xlsx')
